package com.player.dao;

import java.util.List;

import com.googlecode.objectify.Query;
import com.player.entity.Game;

public class GameDAO extends DAO {

	private static final String PROP_OPPONENT_ID = "opponentId";
	private static final String PROP_CREATOR_ID = "creatorId";

	/* pkg */GameDAO() {
	}

	public Game createOrReplace(Long creatorId, Long opponentId) {
		Game game = find(creatorId, opponentId);
		if (game != null && !game.hasResult()) {
			ofy().put(game); // replace existing
		} else {
			game = new Game(creatorId, opponentId);
			ofy().put(game);
		}
		return game;
	}

	public Game update(Game game) {
		Game gameLoaded = get(game.getId());
		if (gameLoaded == null) {
			throw new IllegalArgumentException("Could not find game to be updated: " + game);
		}
		ofy().put(game);
		return game;
	}

	private Game find(Long creatorId, Long opponentId) {
		Query<Game> query = ofy().query(Game.class).filter(PROP_CREATOR_ID, creatorId).filter(PROP_OPPONENT_ID,
				opponentId);
		return query.get();
	}

	/**
	 * @return Game or Null if not found
	 */
	public Game get(Long id) {
		return ofy().find(Game.class, id);
	}

	public List<Game> getByCreator(Long creatorId) {
		Query<Game> query = ofy().query(Game.class).filter(PROP_CREATOR_ID, creatorId);
		return query.list();
	}

	public List<Game> getGamesToBeConfirmed(Long playerId) {
		Query<Game> query = ofy().query(Game.class).filter(PROP_OPPONENT_ID, playerId).filter(
				"result.confirmedByOpponent =", false);
		return query.list();
	}
}
